﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Objects.DataClasses;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Security;
using AppLab.Core;
using AppLab.Data.Models;
using AppLab.Web.Resources;

namespace AppLab.Web
{
    public sealed partial class RolesForUser
    {
        [Key]
        public Guid UserID { get; set; }
        public string Alias { get; set; }
        public string DisplayName { get; set; }
        public int IsRegister { get; set; }
        public int IsTerminalInfo { get; set; }
        public int IsHistory { get; set; }
        public int IsSubmit { get; set; }
        public int IsReview { get; set; }
        public int IsTask { get; set; }
        public int IsPublish { get; set; }
        public int IsRole { get; set; }

        #region 角色管理
        private void Executing(int current, string roleName)
        {
            if (current == 0)
                Roles.RemoveUserFromRole(this.Alias, roleName);

            if (current == 1)
                Roles.AddUserToRole(this.Alias, roleName);
        }

        public bool ToDataBaseFormat(RolesForUser ed)
        {
            try
            {
                if (ed.IsTerminalInfo != this.IsTerminalInfo)
                    Executing(this.IsTerminalInfo, UserRegistrationService.TerminalInfoRole);

                if (ed.IsSubmit != this.IsSubmit)
                    Executing(this.IsSubmit, UserRegistrationService.SumbitRole);

                if (ed.IsReview != this.IsReview)
                    Executing(this.IsReview, UserRegistrationService.ReviewRole);

                if (ed.IsTask != this.IsTask)
                    Executing(this.IsTask, UserRegistrationService.TaskRole);

                if (ed.IsPublish != this.IsPublish)
                    Executing(this.IsPublish, UserRegistrationService.PublishRole);

                if (ed.IsRole != this.IsRole)
                    Executing(this.IsRole, UserRegistrationService.ManagementRole);
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 注销用户

        public bool DeleteUser()
        {
            try
            {
                Membership.Providers["AspNetSqlMembershipProvider"].DeleteUser(this.Alias, false);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("Delete {0} is failed....", this.Alias));
                Log.WriteError(ex.Message);
                Log.WriteError(ex.StackTrace);
                return false;
            }
        }

        #endregion

        #region 重置密码

        public bool ResetPassword(string resetManageName)
        {
            MembershipUser user = Membership.GetUser(this.UserID);
            try
            {
                if (user.IsLockedOut)
                {
                    user.UnlockUser();
                }
                string resetP = Membership.Providers["AspNetSqlMembershipProvider"].ResetPassword(user.UserName, (string)null);
                Membership.Providers["AspNetSqlMembershipProvider"].ChangePassword(user.UserName, resetP, "Password01!");
            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("Reset {0} Password is failed....", this.Alias));
                Log.WriteError(ex.Message);
                Log.WriteError(ex.StackTrace);
                return false;
            }

            string restUserID = "";
            using (var dc = PMSEntities.Create())
            {
                restUserID = dc.aspnet_Users.FirstOrDefault(p => p.UserName == resetManageName).UserId;
            }
            if (!string.IsNullOrEmpty(restUserID))
            {
                MembershipUser resetUser = Membership.GetUser(Guid.Parse(restUserID));
                this.SendEmail(user, resetUser);
            }

            return true;
        }

        #endregion

        #region 发送Email

        private void SendEmail(MembershipUser user, MembershipUser resetUser)
        {
            string toList = user.Email;
            string cCList = resetUser == null ? "" : resetUser.Email;
            string subject = "密码重置成功！";
            //Log1.instance.WriteInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\ResetPassword.htm"));
            string bodyStr = System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\ResetPassword.htm"));
            bodyStr = string.Format(bodyStr, user.UserName);
            MailUtility.SendMail(toList, cCList, subject, bodyStr);
        }

        #endregion

    }
}